package org.setamv.springcloud.hystrix.comprehesive;

import org.setamv.springcloud.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public User getUser(@PathVariable String id) throws Exception {
        Future<User> userFuture = userService.getUser(id);
        User user = userFuture.get();
        return user;
    }

    @RequestMapping(value = "/batch/{ids}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<User> getUser(@PathVariable List<String> ids) throws Exception {
        // 为了演示Hystrix的合并请求，这里每次只获取一个用户信息，从而检测service层有没有将多个请求合并为一个请求
        List<User> users = new ArrayList<>();
        List<Future<User>> userFutures = new ArrayList<>();
        for (String id : ids) {
            Future<User> userFuture = userService.getUser(id);
            userFutures.add(userFuture);
        }
        for (Future<User> userFuture : userFutures) {
            User user = userFuture.get();
            users.add(user);
        }
        return users;
    }
}
